package com.power.sifa.net.dao.impl;

import com.plf.common.domain.BasePageInfo;
import com.plf.common.utils.BeanUtil;
import com.power.sifa.net.dao.Lu_entityormDao;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Repository
public class Lu_entityormDaoImpl implements Lu_entityormDao {
    @Resource
    private EntityManager entityManager;

    @Override
    public <T> List<T> findList(Class<T> clazz, Map<String, Object> params, BasePageInfo pageInfo) {
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<T> query = builder.createQuery(clazz);
        Root<T> root = query.from(clazz);

        if (!params.isEmpty()) {
            // 1. 创建查询对象
            List<Predicate> predicateList = new ArrayList<>();
            // 2. 组装查询条件
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                predicateList.add(builder.equal(root.get(entry.getKey()), entry.getValue()));
            }
            // 3. 转化查询对象格式添加
            if (predicateList.size() > 0) {
                Predicate[] predicates = new Predicate[predicateList.size()];
                for (int i = 0; i < predicates.length; i++) {
                    predicates[i] = predicateList.get(i);
                }
                query.where(predicates);
            }
        }
        // 先查总数
        int total = entityManager.createQuery(query).getResultList().size();
        pageInfo.setAllcount(total);

        String pkfield = BeanUtil.getPkColumn(clazz);
        if (pkfield != null) {
            // 根据id降序
            query.orderBy(builder.desc(root.get(pkfield)));
        }
        int start = (pageInfo.getPageNumber() - 1) * pageInfo.getPageSize();
        List<T> list = entityManager.createQuery(query).setFirstResult(start).setMaxResults(pageInfo.getPageSize()).getResultList();
        return list;
    }


}
